/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* cur1 = l1, *cur2 = l2;
        ListNode* newhead = new ListNode(0);    // 创建一个头结点
        ListNode* tail = newhead;
        int carry = 0; // 进位
        
        // l1 链表没走完 l2 链表没走完 carry 值为0
        while(cur1 || cur2 || carry)
        {
            // 先加上第一个链表
            if(cur1)
            {
                carry += cur1->val;
                cur1 = cur1->next;
            }

            // 再加上第二个链表
            if(cur2)
            {
                carry += cur2->val;
                cur2 = cur2->next;
            }

            tail->next = new ListNode(carry % 10);
            tail = tail->next;
            carry /= 10;
        }
        tail = newhead->next;   // 保存头结点的下一个结点
        delete newhead;

        return tail;
    }
};